/**
 * Created by abiu on 2016-03-03.
 */
var project = require('../model').project;
var api = require('../model').api;

var countsPerPage = 7;

exports.getProjects = function* () {

    var condition = {};
    console.log(this.request.isManager);
    if (this.request.isManager && 1 != this.session.user.user_power)
        condition = {project_create_by: this.session.user._id};
    var from = parseInt(this.params.from);
    var counts = parseInt(this.params.counts);
    try{
        var find = yield project.find(condition).skip(from).limit(counts);
    }
    catch(err){
       find = {err:err,status:500};
    }

    this.send(find);

}

exports.getProject = function* () {

    var condition = {_id:this.params._id};
    console.log(this.request.isManager);
    if (this.request.isManager && 1 != this.session.user.user_power)
        condition = {project_create_by: this.session.user._id};
    try{
        console.log(condition);
        var find = yield project.findOne(condition);
    }
    catch(err){
        find = {err:err,status:500};
    }

    this.send(find);

}
exports.getProjectsCounts = function* (){
    var condition = {};
    if (this.request.isManager && 1 != this.session.user.user_power)
       condition = {project_create_by: this.session.user._id};

    try{
        var find = yield project.count(condition);
    }
    catch(err){
        find = {err:err,status:500};
    }

    this.send(find);
}

exports.addProject = function*() {
    var data = this.request.body;
        data.project_create_by= this.session.user._id;
        data.project_create_at= Date.now();

    try{
        var create = yield  project.create(data);
    }
    catch(err){
        create = {err:err,status:500};
    }
    this.send(create);

}


exports.updateProject = function*() {
    var data = this.request.body;
        data.project_update_at=Date.now();

    try {
        var update = yield project.update({_id: data._id}, {$set:data});
    }
    catch (err) {
        update = {err:err,status:500};
    }

    this.send(update);

}



exports.deleteProject = function* (){
    var body = this.request.body;
    var condition = {"_id":body._id}
    if (1 != this.session.user.user_power)
    condition.project_create_by = this.user._id;
    console.log(condition);
    try {
        var remove = "success";
       yield  project.remove(condition);
        yield api.remove({project_id:body._id})
    }
    catch (err) {
        remove = {err:err,status:500}
    }

    this.send(remove);

}

